<template>
  <div class="content" style="background: #000">
    <background :src="imgData.url" style="z-index: 1" :weather="weather"></background>
    <grid :imgData="imgData" style="position: fixed;left: 0;top: 0;bottom: 0;right: 0;z-index: 2"
      @weather-change="(e) => { weather = e; }"></grid>

    <a-dialog v-model="updateVisible">
      <div class="dialog-title">发现新版本</div>
      <div
        style="text-align: center;display: flex;flex-direction: column;align-items: center;width: 300px;position: relative;">
        <lottie :options="lottieOptions" :width="200" :height="200" style="position: absolute;top: 0;left: 50;" />
        <div style="height: 120px;"></div>
        <p style="text-align: left;" v-html="newVersion.releaseNote"></p>
        <div style="height: 4px;"></div>
        <div style="font-size: 12px;color: var(--font-placeholder-color);">版本号:{{ newVersion.version }}</div>
        <div style="height: 20px;"></div>
        <div style="display: flex;">
          <button class="button btn-default" @click.stop="skip(newVersion.versionNumber)">跳过此版本</button>
          <button class="button btn-primary" @click.stop="download(newVersion.url)">下载更新</button>
        </div>
      </div>
    </a-dialog>

    <div style="position: fixed;right: 10px;bottom: 10px;display: flex;z-index: 99;align-items: center;">

      <div @click="beforeImg" class="button circle" :class="{ 'disabled': imageIdx > 5 || isLoading }">
        <i class="fa-solid fa-chevron-left"></i>
      </div>
      <div @click="afterImg" class="button circle" :class="{ 'disabled': imageIdx <= 0 || isLoading }">
        <i class="fa-solid fa-chevron-right"></i>
      </div>
      <div @click="openUrl(imgData.copyrightlink)" class="button circle">
        <i class="fa-solid fa-question"></i>
      </div>
    </div>
  </div>
</template>
<script setup>
import ADialog from "@/components/a-dialog.vue";
import Grid from "./common/grid.vue";
import Background from "./common/background.vue";
import Lottie from "@/components/lottie.vue";
import { onMounted, ref } from 'vue'
import api from '@/api/bing_server_api'

import updateApi from '@/api/version_api'
import { storage } from "@/lib/storage";
import common from "@/lib/common";

const updateVisible = ref(false);
const imageIdx = ref(0);
const isLoading = ref(false); // 添加图片加载状态变量

const newVersion = ref({
  url: '',
  version: '',
  releaseNote: '',
})

const imgData = ref({
  url: '',
  title: '',
  copyrightlink: '',
  copyright: '',
  versionNumber: 0
})

const weather = ref({
  "cap": "",
  "icon": 0,
  "temp": 0.0,
  "tempDesc": 0,
})

// Lottie 动画配置
const lottieOptions = ref({
  path: '/assets/lottie/new.json',
  loop: true,
  autoplay: true
})

const skip = (versionNumber) => {
  storage.set('skipVersionNumber', versionNumber);
  updateVisible.value = false;
}

const openUrl = (url) => {
  window.open(url, '_blank');
}

const download = (url) => {
  const downloadUrl = url;
  const fileName = 'ava-work-plugin.zip';
  updateVisible.value = false;
  // 使用标准浏览器下载方式
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = fileName; // 建议文件名
  link.style.display = 'none';
  document.body.appendChild(link);

  // 触发点击事件开始下载
  link.click();

  // 清理创建的元素
  setTimeout(() => {
    document.body.removeChild(link);
  }, 100);
}

const checkUpdate = () => {
  updateApi.version((res) => {
    storage.get('skipVersionNumber').then((skipVersionNumber) => {
      if (res.versionNumber == Number(skipVersionNumber)) {
        return;
      }
      if (res.versionNumber > common.versionNumber) {
        newVersion.value = res;
        updateVisible.value = true;
      }
    })
  })
}

const beforeImg = () => {
  if (isLoading.value || imageIdx.value > 5) return; // 如果正在加载，直接返回
  imageIdx.value++
  saveImageIdx(); // 保存当前索引
  loadImage();
}

const afterImg = () => {
  if (isLoading.value || imageIdx.value <= 0) return; // 如果正在加载，直接返回
  imageIdx.value--
  saveImageIdx(); // 保存当前索引
  loadImage();
}

const loadImage = () => {
  isLoading.value = true; // 设置加载状态为true
  api.image(imageIdx.value, (res) => {
    imgData.value = res.images[0];
    isLoading.value = false; // 设置加载状态为false
  }, (error) => {
    console.error('加载图片失败:', error);
    isLoading.value = false; // 即使失败也要设置加载状态为false
  })
}

// 保存imageIdx和当前日期
const saveImageIdx = () => {
  const now = new Date();
  const today = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
  const data = JSON.stringify({
    index: imageIdx.value,
    date: today
  });
  storage.set('imageIdx', data);
}
onMounted(() => {
  checkUpdate();
  storage.get('setting').then((res) => {
    if (!res) {
      return;
    }
    res = JSON.parse(res);
    document.documentElement.setAttribute('theme-mode', res && res.cap ? res.cap : 'light');
  })

  // 加载保存的imageIdx
  storage.get('imageIdx').then((savedData) => {
    const now = new Date();
    const today = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();

    if (savedData) {
      // 尝试解析保存的数据
      let parsedData;
      try {
        parsedData = typeof savedData === 'string' ? JSON.parse(savedData) : savedData;

        // 检查是否是当天保存的数据
        if (parsedData.date === today) {
          imageIdx.value = parsedData.index || 0;
        } else {
          // 不是当天，重置为0
          imageIdx.value = 0;
          // 保存新的状态
          saveImageIdx();
        }
      } catch (error) {
        console.error('解析保存的imageIdx失败:', error);
        imageIdx.value = 0;
      }
    }

    loadImage();
  }).catch(() => {
    // 如果获取失败，使用默认值并加载图片
    imageIdx.value = 0;
    loadImage();
  });

  // 记录当天第一次启动时间
  storage.get('startup-time').then((ts) => {
    const now = new Date();
    const today = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
    let lastDate = '';
    if (ts) {
      const last = new Date(Number(ts) * 1000);
      lastDate = last.getFullYear() + '-' + (last.getMonth() + 1) + '-' + last.getDate();
    }
    if (today !== lastDate) {
      storage.set('startup-time', Math.floor(now.getTime() / 1000));
    }
  });
})
</script>
<style scoped lang="less">
@import "home.less";
</style>
<style lang="less">
.dialog {
  label {
    font-weight: normal;
    font-size: 14px;
  }
}

.button.circle.disabled {
  background-color: var(--card-background-color);
  color: var(--font-placeholder-color);
}

.button.circle {
  transition: all 0.2s ease-in-out;
  width: 30px;
  height: 30px;
  padding: 0;
  border-radius: 50%;
  line-height: 30px;
  text-align: center;
  background-color: var(--card-background-color);
}

.link:hover {
  opacity: 1;
}

.link {
  opacity: 0.8;
  transition: all 0.2s ease-in-out;
  font-size: 14px;
  cursor: pointer;
  color: var(--font-color);
  text-shadow: 0 0 1px var(--shadow-color);
}
</style>